import { Messages } from "../../constants/Messages";

const { ccclass, property } = cc._decorator;

export const enum TouchEventType {
    DblClick = 0,
    LongPress,
};

@ccclass
export default class TouchEvent extends cc.Component {

    @property(cc.Node)
    eventNode: cc.Node = null;

    _dblClickThreshold: number = .15;
    _longPressThreshold: number = 1;

    _lastTouchTime: number = -1;

    onLoad() {
        this.node.on(cc.Node.EventType.TOUCH_START, this.onTouchStart, this);
        this.node.on(cc.Node.EventType.TOUCH_END, this.onTouchEnd, this);
        this.node.on(cc.Node.EventType.TOUCH_CANCEL, this.onTouchCancel, this);
    }

    onTouchStart(event: cc.Event.EventTouch) {
        const currentTime = new Date().getTime() / 1000;
        if (currentTime - this._lastTouchTime <= this._dblClickThreshold) {// 触发双击逻辑
            cc.isValid(this.eventNode) && this.eventNode.emit(Messages.Nodes.DblClick);
        } else {
            // 启动长按计时器
            this.scheduleOnce(this.onLongPress, this._longPressThreshold);
        }
    }

    onTouchEnd() {
        this.unschedule(this.onLongPress); // 取消长按计时器
        this._lastTouchTime = new Date().getTime() / 1000;
    }

    onTouchCancel() {
        this.unschedule(this.onLongPress); // 取消长按计时器
    }

    onLongPress() {// 触发长按逻辑
        cc.isValid(this.eventNode) && this.eventNode.emit(Messages.Nodes.LongPress);
    }
}
